package com.qf.cardlike.service.impl;

import com.google.common.base.Joiner;
import com.qf.cardlike.domain.User;
import com.qf.cardlike.mapper.UserMapper;
import com.qf.cardlike.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zed
 * @date 2022/5/16 17:12
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        List<User> users = userMapper.selectByName(username);
        for (User user : users) {
            if (Objects.equals(password, user.getPassword())) {
                return user;
            }
        }
        return null;
    }

    @Override
    public User likeCard(Integer userId, Integer cardId, Boolean like) {
        // 喜欢哪个名片  不喜欢[删除]哪个名片
        User user = userMapper.selectByPrimaryKey(Long.valueOf(userId));
        // 喜欢的哪些名字 1,2,3,4
        String likedIds = user.getLiked();
        if (like) {
            // 喜欢哪个名片 liked 追加名片ID
            likedIds = StringUtils.isEmpty(likedIds) ? cardId.toString() : likedIds + "," + cardId;
        } else {
            // 如果不喜欢哪个名片
            // 说明：Arrays.asList() 方法返回的List对象是一个Arrays的内部类，这个内部类不支持集合的添加add()/移除remove()操作
            List<String> likedIdList = Arrays.stream(likedIds.split(",")).collect(Collectors.toList());
            likedIdList.remove(cardId.toString());
            // 把这个集合转换为逗号分割的字串 google提供了一个工具guava这个工具
            likedIds = Joiner.on(",").join(likedIdList);
        }
        user.setLiked(likedIds);
        userMapper.updateByPrimaryKeySelective(user);
        return user;
    }

}
